package org.budo.netty.servlet.util;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.budo.netty.servlet.server.handler.servlet.BudoServletRequest;

/**
 * @author lmw
 */
public class RequestUtil {
    public static BudoServletRequest getBudoServletRequest(ServletRequest request) {
        if (request instanceof BudoServletRequest) {
            return (BudoServletRequest) request;
        }

        if (request instanceof HttpServletRequestWrapper) {
            ServletRequest servletRequest = ((HttpServletRequestWrapper) request).getRequest();
            return getBudoServletRequest(servletRequest);
        }

        throw new RuntimeException("#35 request=" + request);
    }

    public static String getCharacterEncodingFromContentType(HttpServletRequest request) {
        String contentType = request.getContentType();
        if (null == contentType) {
            return null;
        }

        int charsetPos = contentType.indexOf("charset=");
        if (charsetPos == -1) {
            return "UTF-8";
        }

        return contentType.substring(charsetPos + 8);
    }
}